package com.ypf.rpc.nettyHandler;


import com.ypf.rpc.factory.RegisterFactory;
import com.ypf.rpc.message.RpcRegisterRequestMessage;
import com.ypf.rpc.message.RpcRegisterResponseMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetSocketAddress;

@ChannelHandler.Sharable
public class RpcRegisterRequestMessageHandler extends SimpleChannelInboundHandler<RpcRegisterRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRegisterRequestMessage message) throws Exception {
        RpcRegisterResponseMessage rpcRegisterResponseMessage = new RpcRegisterResponseMessage();

        // 设置请求序列号
        rpcRegisterResponseMessage.setSequenceId(message.getSequenceId());

        // 保存该服务器与注册中心的channel
        Channel channel = ctx.channel();

        RegisterFactory registerFactory = new RegisterFactory();

        // 根据发过来的注册信息创建 inetSocketAddress 对象
        InetSocketAddress inetSocketAddress =new InetSocketAddress(message.getServerHost(),message.getServerPort());

        for (String serverName : message.getServerNames()) {
            registerFactory.addServer(channel,serverName,inetSocketAddress);
        }

        rpcRegisterResponseMessage.setSuccess(true);
        rpcRegisterResponseMessage.setReason("");

        ctx.writeAndFlush(rpcRegisterResponseMessage);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("通道:"+ctx.channel()+" 从注册中心断开");
        RegisterFactory registerFactory = new RegisterFactory();
        registerFactory.removeServer(ctx.channel());
        super.channelInactive(ctx);
    }
}
